import Request from 'luch-request'
import cache from '@/utils/cache'
import store from '@/store'
import { localStorage } from 'mp-storage'
import config from '@/config'
import {
  handleNotLogin,
  handleNotReport,
  handleNotFace,
  handleNotUser,
  handleNetError,
} from './errorHandle'

const request = new Request({
  baseURL: config.apiBaseURL,
  timeout: 90000,
})

request.interceptors.request.use(
  (config) => {
    console.log('api 发起请求', config.method, config.url, config)
    const token = cache.Authorization.get()
    if (token) {
      config.header.Authorization = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    if (config.custom.needLoading) {
      uni.showLoading({
        title: '稍等',
        mask: true,
      })
    }
    return {
      ...config,
      params: {
        ...(config.params || {}),
        _t: Date.now(),
      },
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    console.log(
      'api 收到响应',
      response.config.method,
      response.config.url,
      response
    )
    const { data } = response
    uni.hideLoading()
    if (data.code !== 200) {
      if (data.code === 401) {
        localStorage.clear()
        store.commit('SET_ISLOGIN', false)
        handleNotLogin()
      } else if (data.code === 402) {
        handleNotReport()
      } else if (data.code === 406) {
        handleNotFace()
      } else if (data.code === 407) {
        handleNotUser()
      } else {
        uni.showModal({
          title: '错误',
          content: data.message,
          showCancel: false,
        })
      }
      return Promise.reject(data)
    } else {
      return data
    }
  },
  (error) => {
    uni.hideLoading()
    handleNetError()
    return Promise.reject(error)
  }
)

export default request
